package com.woniu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

@Controller
public class uploadController {
    @RequestMapping("upload")
    public String upload(MultipartFile photo, HttpServletRequest req){
        //将上传文件对象解析到项目发布的目录下
        //获得原文件的名字 1.png
        String filename = photo.getOriginalFilename();
        //获得后缀
        String suffix=filename.substring(filename.lastIndexOf("."));
        //唯一文件名 xxxxxxxxxxxxx.png
        filename= UUID.randomUUID()+suffix;
        //获得项目中上传文件的目录
        String realPath=req.getServletContext().getRealPath("/upload");
        File dir = new File(realPath);
        if (dir.exists()){
            dir.mkdirs();
        }
        //有了目录，也有文件名，声明文件目标对象
        File targetFile = new File(dir, filename);
        try {
           photo.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "upload";
    }
}
